package org.endy.leisure.diaTracker.service

import org.endy.leisure.diaTracker.entity.question.Answer
import org.endy.leisure.diaTracker.entity.question.Question
import org.endy.leisure.diaTracker.repository.QuestionRepository
import org.springframework.stereotype.Service
import org.springframework.transaction.annotation.Transactional

@Service
class QuestionService(private val questionRepository: QuestionRepository) {

    /**
     * 用提交问题
     */
    fun createQuestion(question: Question): Question {
        return questionRepository.save(question)
    }

    /**
     * 用户查询自己的问题
     */
    @Transactional(readOnly = true)
    fun findUserQ(userId: Long): List<Question> {
        return questionRepository.findQuestionByUserId(userId)
    }

    /**
     * 查询所有问题
     */
    fun findAllQuestion(): List<Question> {
        return questionRepository.findAll()
    }

    /**
     * 查询所有未回答的问题列表
     */
    fun findAllNoAnswerQuestion(): List<Question> {
        return questionRepository.findNoAnswerQuestions()
    }

    /**
     * 医生回答问题
     */
    fun answerQ(questionId: Long, userId: Long, content: String) {

        questionRepository.findById(questionId).ifPresent { question ->
            with(question) {
                answer = Answer(content = content, userId = userId)
            }
            questionRepository.save(question)
        }

    }

}